package com.dullong.firedocmanager.Controller.page;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.dullong.firedocmanager.bean.Document;
import com.dullong.firedocmanager.lucene4.LuceneSearchService;
import com.dullong.firedocmanager.lucene4.Searchable;
import com.dullong.firedocmanager.service.DocumentService;
import com.dullong.firedocmanager.util.OptionUtil;
import com.dullong.firedocmanager.util.json.SendJsonUtil;

@Controller
public class DocumentPage {

	@Autowired
	DocumentService documentService;
	@Autowired
	LuceneSearchService luceneSearchService;

	@RequestMapping(value = "/show/{ID}.html", method = RequestMethod.GET)
	public ModelAndView home(HttpServletRequest request,
			HttpServletResponse response, @PathVariable Long ID)
			throws IOException {
		ModelAndView view = new ModelAndView();
		Document document = documentService.get(ID);
		Long indexNum = documentService.getIndexNum();
		Integer dnum;
		if (indexNum > ID) {
			dnum = (int) (long) ID;
		} else {
			dnum = (int) (indexNum - 1);
		}
		List<Searchable> sm = luceneSearchService.moreLikeThis(dnum, 10,
				new String[] { "title", "detail" });
		List<Document> similars = new ArrayList<Document>();
		for (Searchable s : sm) {
			similars.add(documentService.get(s.id()));
		}
		view.addObject("document", document);
		view.addObject("similars", similars);
		view.setViewName("document-page");
		return view;
	}

	@ResponseBody
	@RequestMapping(value = "/show/down-{ID}.json", method = RequestMethod.POST)
	public void getDownUrl(@PathVariable Long ID,
			@RequestParam(value = "type", required = true) String type,
			HttpServletRequest request, HttpServletResponse response) {
		String downUrl = documentService.getDownUrl(ID, type);
		downUrl = FilenameUtils.normalize(downUrl, true);
		String jsonString = "{\"urlString\":\"" + downUrl + "\"}";
		SendJsonUtil.sendJson(jsonString, response);
	}

	/**
	 * 文件下载
	 * 
	 * @param fname
	 *            文件名称（含后缀）
	 * @throws IOException
	 */
	@RequestMapping("/down/{ID}.html")
	public ResponseEntity<byte[]> downFile(@PathVariable Long ID,
			@RequestParam(value = "type", required = true) String type,
			HttpServletRequest request, HttpServletResponse response) {
		String option = OptionUtil.getOption("opload_filePath");
		String downUrl = documentService.getDownUrl(ID, type);
		downUrl = option + File.separator + FilenameUtils.normalize(downUrl);
		File f = new File(downUrl);

		String downFileName = f.getName();

		// Http响应头
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		headers.setContentDispositionFormData("attachment", downFileName);

		try {
			return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(f),
					headers, HttpStatus.OK);
		} catch (Exception e) {
			e.printStackTrace();
			// 日志
			// TODO
		}

		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		headers.setContentDispositionFormData("attachment", "error.txt");
		return new ResponseEntity<byte[]>("文件不存在.".getBytes(), headers,
				HttpStatus.OK);
	}
}
